package com.itqn.dao.Impl;

import java.sql.*;

/***
 * 封装一个底层类
 * 用于操作数据库
 */
public class BaseDao {
    Connection connection;
    PreparedStatement stmt;
    ResultSet rs = null;

    //读取数据源
    public BaseDao() throws Exception {
        //通过jdbc 把数据库中books 的数据读取出来
        String driver = Util_Properties.getInstance().getValue("db.driver");
        String url = Util_Properties.getInstance().getValue("db.url");
        String name = Util_Properties.getInstance().getValue("db.name");
        String pass = Util_Properties.getInstance().getValue("db.pass");
        Class.forName(driver);
        connection =
                DriverManager.getConnection(url, name, pass);
    }

    //读数据方法
    public ResultSet getlist(String sql, Object[] objects) throws SQLException {

        stmt = connection.prepareStatement(sql);
        for (int i = 0; i < objects.length; i++) {
            stmt.setObject(i + 1, objects[i]);
        }
        rs = stmt.executeQuery();
        return rs;
    }

    //增删改方法
    public int update(String sql, Object[] objects) throws SQLException {
        stmt = connection.prepareStatement(sql);
        for (int i = 0; i < objects.length; i++) {
            stmt.setObject(i + 1, objects[i]);
        }
        int result = stmt.executeUpdate();
        return result;
    }

    //关闭资源
    public void close() throws SQLException {
        if (connection != null) {
            connection.close();
        }
        if (stmt != null) {
            stmt.close();
        }
        if (rs != null) {
            rs.close();
        }
    }
}
